package com.my.netty.nio.net.multithread;


import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class MultiThreadNioServer {

    /*
        多线程NIO服务端，1个Boss线程负责处理accept事件，多个Worker线程负责处理读写事件
        每个线程都有自己的selector，可监听多个channel
     */
    public static void main(String[] args) throws IOException {
        //主线程就是boss线程，修改线程名
        Thread.currentThread().setName("Boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8080));

        //boss线程只负责处理accept事件
        Selector bossSelector = Selector.open();
        ssc.register(bossSelector, SelectionKey.OP_ACCEPT, null);

        //创建固定数量的Worker，实际中可设置worker数量为cpu核心数：Runtime.getRuntime().availableProcessors()
        // 注意这个方法在docker容器上拿到的不是容器申请的CPU个数，而是物理机的CPU个数
        Worker[] workers = new Worker[2];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("Worker-" + i);
        }

        //轮询计数器，用于将SocketChannel轮询均分给Worker
        AtomicInteger index = new AtomicInteger();

        while (true) {
            log.debug("BossSelector等待事件...");
            bossSelector.select();

            Iterator<SelectionKey> iter = bossSelector.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    log.debug("获取客户端连接:{}", sc.getRemoteAddress());

                    //将SocketChannel均分给Worker线程处理（关联到worker的selector）
                    log.debug("before register");
                    sc.configureBlocking(false);
//                    worker.register(sc);
                    workers[index.getAndIncrement() % workers.length].register(sc);
                    //注意：如果worker线程中的workerSelector.select()先执行，下面sc.register()就会阻塞，导致无法注册
                    //必须保证sc.register先执行，workerSelector.select()后执行；netty的方法：将sc.register()放到worker线程执行
//                    sc.register(worker.workerSelector, SelectionKey.OP_READ, null);
                    //如果没有线程通行，可能执行不到下面这行
                    log.debug("after register");
                }
                iter.remove();
            }
        }
    }

    /*
        处理读写事件的worker
     */
    private static class Worker implements Runnable {
        //worker线程
        public Thread thread;
        //worker的selector
        private Selector workerSelector;
        //worker名称
        private String name;

        private volatile boolean started = false;

        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();

        public Worker(String name) {
            this.name = name;
        }

        //初始化线程和selector
        public synchronized void register(SocketChannel sc) throws IOException {
            if (!started) {
                this.thread = new Thread(this, name);
                this.workerSelector = Selector.open();
                //启动线程
                this.thread.start();
                this.started = true;
            }
            //放在这里还是被Boss线程执行，这里用一个队列封装任务，让Worker线程从队列取任务并执行
//            sc.register(this.workerSelector, SelectionKey.OP_READ, null);
            //使用队列添加任务
            queue.add(() -> {
                try {
                    sc.register(this.workerSelector, SelectionKey.OP_READ, null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            //唤醒workerSelector.select()
            this.workerSelector.wakeup();
        }

        @Override
        public void run() {
            //worker线程执行的任务
            while (true) {
                try {
                    log.debug("{}-Selector等待事件...", name);
                    workerSelector.select();

                    //worker线程将上面队列的Runnable取出来执行；通过workerSelector.wakeup()可以让上面select()方法结束阻塞，完成下面的注册
                    Runnable runnable = queue.poll();
                    if (runnable != null) {
                        runnable.run();
                    }

                    Iterator<SelectionKey> iter = workerSelector.selectedKeys().iterator();
                    while (iter.hasNext()) {
                        SelectionKey key = iter.next();
                        if (key.isReadable()) {
                            SocketChannel sc = (SocketChannel) key.channel();
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            sc.read(buffer);
                            buffer.flip();
                            log.debug("获取客户端{}发送数据:{}", sc.getRemoteAddress(), Charset.defaultCharset().decode(buffer));
                        }
                        iter.remove();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
